package deibay.server.io;

import java.util.List;

import org.jdom.Element;

import deibay.users.Admin;
import deibay.users.Bidder;
import deibay.users.Seller;
import deibay.users.User;

public class XmlUser {

	private Element user = null;
	
	public XmlUser(String login, String password, String email, String address, String role)
	{
		user = new Element("User");			
		Element eLogin = new Element("login");
		eLogin.addContent(login);
		Element ePass = new Element("pass");
		ePass.addContent(password);
		Element eMail = new Element("email");
		eMail.addContent(email);
		Element eAddress = new Element("address");
		eAddress.addContent(address);
		Element eRole = new Element("role");
		eRole.addContent(role);
		user.addContent(eLogin);
		user.addContent(ePass);
		user.addContent(eMail);
		user.addContent(eAddress);
		user.addContent(eRole);		
	}
	
	public XmlUser(Element user)
	{
		this.user = user;
	}
	
	
	public User xmlToObject()
	{
		User u = null;
		
		List<Element> elements = user.getChildren();
		String login = "", password = "", email = "", address = "", role =""; 
		for(Element e: elements)
		{
			if(e.getName().equals("login"))
			{
				login = e.getValue();
			}
			else if(e.getName().equals("password"))
			{
				password = e.getValue();
			}
			else if(e.getName().equals("email"))
			{
				email = e.getValue();
			}
			else if(e.getName().equals("address"))
			{
				address = e.getValue();
			}
			else if(e.getName().equals("role"))
			{
				role = e.getValue();
			}
		}
		
		if(role.equals("admin"))		
			u = new Admin(login, password, email, address);		
		else if(role.equals("seller"))
			u = new Seller(login, password, email, address);
		else if(role.equals("bidder"))
			u = new Bidder(login, password, email, address);
		
		return u;
	}
	
	public Element getXmlUser()
	{
		return this.user;
	}
}
